package com.bawei.module_mine.utils

import com.bawei.lib_storage.database.HistoryManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * 历史记录工具类
 * 用于在视频播放时记录观看历史
 */
object HistoryUtils {
    
    /**
     * 记录视频观看历史
     * 在视频开始播放时调用
     */
    fun recordVideoHistory(
        videoId: Int,
        title: String,
        description: String,
        coverUrl: String,
        videoUrl: String,
        userId: String = "default_user"
    ) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                HistoryManager.addHistory(
                    videoId = videoId,
                    title = title,
                    description = description,
                    coverUrl = coverUrl,
                    videoUrl = videoUrl,
                    userId = userId
                )
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    /**
     * 更新视频观看时长
     * 在视频播放结束时调用
     */
    fun updateWatchDuration(
        videoId: Int,
        watchDurationMs: Long,
        userId: String = "default_user"
    ) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                // 获取现有历史记录
                val existingHistory = HistoryManager.getAllHistory(userId)
                    .find { it.videoId == videoId }
                
                existingHistory?.let { history ->
                    // 更新观看时长
                    HistoryManager.addHistory(
                        videoId = history.videoId,
                        title = history.title,
                        description = history.description,
                        coverUrl = history.coverUrl,
                        videoUrl = history.videoUrl,
                        userId = history.userId,
                        watchDuration = watchDurationMs
                    )
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
    
    /**
     * 检查视频是否在历史记录中
     */
    fun isVideoInHistory(
        videoId: Int,
        userId: String = "default_user",
        callback: (Boolean) -> Unit
    ) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                val isInHistory = HistoryManager.isInHistory(videoId, userId)
                callback(isInHistory)
            } catch (e: Exception) {
                e.printStackTrace()
                callback(false)
            }
        }
    }
    
    /**
     * 删除指定视频的历史记录
     */
    fun removeVideoHistory(
        videoId: Int,
        userId: String = "default_user"
    ) {
        CoroutineScope(Dispatchers.IO).launch {
            try {
                HistoryManager.removeHistory(videoId, userId)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
    }
} 